package com.googlecode.gwt4gae.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.google.inject.Guice;
import com.google.inject.servlet.GuiceFilter;

public class Gwt4gaeGuiceFilter extends GuiceFilter {
	private static Map<String,String> SERVICE_CACHE = new HashMap<String,String>();
	public void doFilter(ServletRequest servletRequest,
		      ServletResponse servletResponse, FilterChain filterChain)
		      throws IOException, ServletException {
		HttpServletRequest hsr = (HttpServletRequest) servletRequest;		
		
		String url = hsr.getServletPath();
		if (url == null || !url.endsWith("ServiceImpl")) {
			return;
		}
		String serviceImpl = url.substring(url.indexOf("/", 2) + 1).replace("/", ".");
		if (SERVICE_CACHE.get(url) == null) {
			Guice.createInjector(new Gwt4gaeServletModule(url,serviceImpl));
			SERVICE_CACHE.put(url, serviceImpl);
		} else {
			//do nothing
		}
		
		super.doFilter(servletRequest, servletResponse, filterChain);
	}
}
